package Day19;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo08 {
    public static void main(String[] args) {
        //显示锁  lock
        //同步代码块和同步方法都是隐式锁
        Ticket t = new Ticket();
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();

    }
    static class Ticket implements Runnable {
        private int count = 10;
        private Lock l = new ReentrantLock(true);//true表示公平锁  先到先得后面排队
        @Override
        public void run() {
            aa:while (count>0) {
                    l.lock();
                    System.out.println("正在准备卖票");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count--;
                    if(count < 0){
                        //l.unlock();
                        break aa;
                    }
                    System.out.println(Thread.currentThread().getName() + "出票成功,余票：" + count);
                    l.unlock();
                }
            }
        }
    }
